package com.qiaoba.module.system.controller;

import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageHelper;
import com.qiaoba.api.log.annotation.Log;
import com.qiaoba.api.log.enums.BusinessType;
import com.qiaoba.api.system.entity.dto.SysUserDTO;
import com.qiaoba.api.system.entity.dto.UserResetPwdDTO;
import com.qiaoba.api.system.entity.dto.UserUpdateStatusDTO;
import com.qiaoba.api.system.entity.vo.SysUserVO;
import com.qiaoba.common.base.entity.AjaxResult;
import com.qiaoba.common.base.entity.Result;
import com.qiaoba.common.base.validate.AddGroup;
import com.qiaoba.common.base.validate.EditGroup;
import com.qiaoba.common.database.entity.PageQuery;
import com.qiaoba.common.database.entity.PageResult;
import com.qiaoba.module.system.entity.SysUser;
import com.qiaoba.module.system.entity.param.SysPostParam;
import com.qiaoba.module.system.entity.param.SysRoleParam;
import com.qiaoba.module.system.entity.param.SysUserParam;
import com.qiaoba.module.system.entity.template.SysUserImport;
import com.qiaoba.module.system.service.*;
import com.qiaoba.poi.excel.util.ExcelUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springdoc.api.annotations.ParameterObject;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * 用户管理 web层
 *
 * @author ailanyin
 * @date 2023-09-24 13:13:15
 */
@Validated
@RestController
@RequestMapping("/system/user")
@Tag(name = "用户管理")
@RequiredArgsConstructor
public class SysUserController {

    private final SysUserService sysUserService;
    private final SysRoleService sysRoleService;
    private final SysPostService sysPostService;
    private final SysUserPostService sysUserPostService;
    private final SysUserRoleService sysUserRoleService;
    private final SysUserImportService sysUserImportService;

    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PreAuthorize("hasAuthority('system:user:add')")
    @PostMapping
    @Operation(summary = "新增用户")
    public Result add(@Validated(AddGroup.class) @RequestBody SysUserDTO dto) {
        return Result.toAjax(sysUserService.saveOrUpdate(dto, false));
    }

    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PreAuthorize("hasAuthority('system:user:edit')")
    @PutMapping
    @Operation(summary = "修改用户")
    public Result edit(@Validated(EditGroup.class) @RequestBody SysUserDTO dto) {
        return Result.toAjax(sysUserService.saveOrUpdate(dto, true));
    }

    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @PreAuthorize("hasAuthority('system:user:resetPwd')")
    @PutMapping("/resetPwd")
    @Operation(summary = "重置密码")
    public Result resetPwd(@Validated @RequestBody UserResetPwdDTO dto) {
        return Result.toAjax(sysUserService.resetPwd(dto));
    }

    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @PreAuthorize("hasAuthority('system:user:edit')")
    @PutMapping("/changeStatus")
    @Operation(summary = "更改状态")
    public Result changeStatus(@RequestBody UserUpdateStatusDTO dto) {
        return Result.toAjax(sysUserService.updateStatus(dto));
    }

    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @PreAuthorize("hasAuthority('system:user:remove')")
    @DeleteMapping("/{userIds}")
    @Operation(summary = "删除用户")
    public Result remove(@PathVariable List<String> userIds) {
        return Result.toAjax(sysUserService.deleteByIds(userIds));
    }

    @GetMapping("/list")
    @Operation(summary = "获取列表")
    public PageResult<SysUserVO> list(@ParameterObject SysUserParam param, @ParameterObject PageQuery pageQuery) {
        PageHelper.startPage(pageQuery.getPageNum(), pageQuery.getPageSize());
        List<SysUserVO> list = sysUserService.selectVoList(param);
        return PageResult.build(list);
    }

    @PreAuthorize("hasAuthority('system:user:query')")
    @GetMapping(value = {"/", "/{userId}"})
    @Operation(summary = "获取详情")
    public AjaxResult getInfo(@PathVariable(value = "userId", required = false) String userId) {
        AjaxResult ajax = AjaxResult.success();
        ajax.put("roles", sysRoleService.selectList(new SysRoleParam()));
        ajax.put("posts", sysPostService.selectList(new SysPostParam()));
        if (StrUtil.isNotBlank(userId)) {
            SysUser sysUser = sysUserService.selectById(userId, false);
            ajax.put(AjaxResult.DATA_TAG, sysUser);
            ajax.put("postIds", sysUserPostService.selectPostIdsByUserId(userId));
            ajax.put("roleIds", sysUserRoleService.selectRoleIdsByUserId(userId, null));
        }
        return ajax;
    }

    @Log(title = "用户管理", businessType = BusinessType.EXPORT)
    @PreAuthorize("hasAuthority('system:user:export')")
    @PostMapping("/export")
    @Operation(summary = "导出用户")
    public void export(HttpServletResponse response, SysUserParam param) {
        List<SysUserVO> list = sysUserService.selectVoList(param);
        ExcelUtil.exportExcel(list, SysUserVO.class, "用户数据", response);
    }

    @PostMapping("/importTemplate")
    @Operation(summary = "导出模板")
    public void importTemplate(HttpServletResponse response) {
        ExcelUtil.exportExcel(new ArrayList<>(), SysUserImport.class, "用户导入模板-(*)必填", response);
    }

    @Log(title = "用户管理", businessType = BusinessType.IMPORT)
    @PreAuthorize("hasAuthority('system:user:import')")
    @PostMapping("/importData")
    @Operation(summary = "导入用户")
    public Result importData(MultipartFile file) throws Exception {
        List<SysUserImport> list = ExcelUtil.importExcel(file, SysUserImport.class);
        String msg = sysUserImportService.importUserData(list);
        return Result.success(msg);
    }
}
